package com.blog.cmrpersonalblog.service.impl;

import com.blog.cmrpersonalblog.dto.notification.respnose.NotificationResponse;
import com.blog.cmrpersonalblog.service.WebSocketNotificationService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * WebSocket通知推送服务实现类
 * 使用异步推送，避免阻塞业务线程
 */
@Slf4j
@Service
public class WebSocketNotificationServiceImpl implements WebSocketNotificationService {

    @Resource
    private SimpMessagingTemplate messagingTemplate;

    /**
     * 异步推送通知给指定用户
     * 使用@Async注解，在独立线程池中执行，不阻塞业务线程
     */
    @Async("webSocketTaskExecutor")
    @Override
    public void pushNotificationToUser(Long userId, NotificationResponse notification) {
        try {
            log.info("推送通知给用户: userId={}, notificationId={}, type={}",
                    userId, notification.getId(), notification.getType());

            // 向指定用户推送通知
            // 目标地址: /user/{userId}/queue/notifications
            messagingTemplate.convertAndSendToUser(
                    userId.toString(),
                    "/queue/notifications",
                    notification
            );

            log.debug("通知推送成功: userId={}, notificationId={}", userId, notification.getId());
        } catch (Exception e) {
            log.error("推送通知失败: userId={}, notificationId={}", userId, notification.getId(), e);
        }
    }

    /**
     * 异步广播通知给所有用户
     * 使用@Async注解，在独立线程池中执行，不阻塞业务线程
     */
    @Async("webSocketTaskExecutor")
    @Override
    public void broadcastNotification(NotificationResponse notification) {
        try {
            log.info("广播通知: notificationId={}, type={}",
                    notification.getId(), notification.getType());

            // 向所有订阅了 /topic/notifications 的用户广播通知
            messagingTemplate.convertAndSend("/topic/notifications", notification);

            log.debug("通知广播成功: notificationId={}", notification.getId());
        } catch (Exception e) {
            log.error("广播通知失败: notificationId={}", notification.getId(), e);
        }
    }

    /**
     * 异步推送未读数量给指定用户
     * 使用@Async注解，在独立线程池中执行，不阻塞业务线程
     */
    @Async("webSocketTaskExecutor")
    @Override
    public void pushUnreadCount(Long userId, Integer unreadCount) {
        try {
            log.debug("推送未读数量给用户: userId={}, unreadCount={}", userId, unreadCount);

            Map<String, Object> message = new HashMap<>();
            message.put("unreadCount", unreadCount);
            message.put("timestamp", System.currentTimeMillis());

            // 向指定用户推送未读数量
            // 目标地址: /user/{userId}/queue/unread-count
            messagingTemplate.convertAndSendToUser(
                    userId.toString(),
                    "/queue/unread-count",
                    message
            );

        } catch (Exception e) {
            log.error("推送未读数量失败: userId={}, unreadCount={}", userId, unreadCount, e);
        }
    }
}

